from server import app, init_scheduler, stop_scheduler
import os
import signal
import sys
from loguru import logger

# 初始化调度器
init_scheduler()


def signal_handler(sig, frame):
    """信号处理函数，用于优雅关闭"""
    logger.info("收到关闭信号，正在停止应用...")
    stop_scheduler()
    logger.info("应用已停止")
    sys.exit(0)


# 注册信号处理器
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

# 获取端口和调试模式配置
port = int(os.environ.get("PORT", 13428))
debug = bool(os.environ.get("DEBUG", False))

if __name__ == "__main__":
    logger.info(f"启动Flask应用，端口: {port}, 调试模式: {debug}")
    try:
        app.run(host="0.0.0.0", port=port, debug=debug)
    except KeyboardInterrupt:
        logger.info("应用被用户中断")
        stop_scheduler()
    except Exception as e:
        logger.error(f"应用运行出错: {e}")
        stop_scheduler()
        sys.exit(1)
